import { useState, useEffect } from 'react';
import { Button } from './components/ui/Button';
import { Card } from './components/ui/Card';
import { Avatar } from './components/ui/Avatar';
import { Badge } from './components/ui/Badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './components/ui/Tabs';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import { PieChart, Pie, Cell, ResponsiveContainer as PieResponsiveContainer } from 'recharts';
import { Plus, Trash2, Settings, Search, ChevronRight, FileText, Image, Activity, Clock } from 'lucide-react';
import { useSession } from 'next-auth/react';
import { redirect } from 'next/navigation';

// 模拟数据
const recentProjects = [
  {
    id: '1',
    name: '图像分类 - 猫狗识别',
    type: 'image_classification',
    status: 'completed',
    progress: 100,
    createdAt: '2023-12-10',
    metrics: { accuracy: 0.92, loss: 0.21 }
  },
  {
    id: '2',
    name: '文本分类 - 情感分析',
    type: 'text_classification',
    status: 'running',
    progress: 65,
    createdAt: '2023-12-11',
    metrics: { accuracy: 0.78, loss: 0.45 }
  },
  {
    id: '3',
    name: '目标检测 - 物体识别',
    type: 'image_classification',
    status: 'pending',
    progress: 0,
    createdAt: '2023-12-12',
    metrics: {}
  },
];

const usageStats = [
  { name: '周一', 训练时长: 4.5, 模型数量: 3 },
  { name: '周二', 训练时长: 6.2, 模型数量: 5 },
  { name: '周三', 训练时长: 3.8, 模型数量: 2 },
  { name: '周四', 训练时长: 8.1, 模型数量: 6 },
  { name: '周五', 训练时长: 5.3, 模型数量: 4 },
];

const taskDistribution = [
  { name: '图像分类', value: 55 },
  { name: '文本分类', value: 35 },
  { name: '其他', value: 10 },
];

const COLORS = ['#2563eb', '#10b981', '#6b7280'];

export default function Dashboard() {
  const { data: session } = useSession();
  const [searchTerm, setSearchTerm] = useState('');
  const [filteredProjects, setFilteredProjects] = useState(recentProjects);

  // 如果用户未登录，重定向到登录页
  useEffect(() => {
    if (!session) {
      redirect('/login');
    }
  }, [session]);

  // 处理搜索
  useEffect(() => {
    if (searchTerm) {
      setFilteredProjects(
        recentProjects.filter(project => 
          project.name.toLowerCase().includes(searchTerm.toLowerCase())
        )
      );
    } else {
      setFilteredProjects(recentProjects);
    }
  }, [searchTerm]);

  // 处理创建新项目
  const handleCreateProject = () => {
    redirect('/create-project');
  };

  // 处理项目点击
  const handleProjectClick = (projectId: string) => {
    redirect(`/project/${projectId}`);
  };

  if (!session) {
    return null; // 重定向中
  }

  return (
    <div className="space-y-6">
      {/* 页面标题和操作按钮 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">控制台</h1>
          <p className="text-gray-500 mt-1">欢迎回来，{session.user?.name || session.user?.email}</p>
        </div>
        <div className="flex space-x-3">
          <Button 
            onClick={handleCreateProject} 
            className="bg-primary hover:bg-primary/90 text-white"
          >
            <Plus className="h-4 w-4 mr-2" />
            创建新项目
          </Button>
        </div>
      </div>

      {/* 系统状态卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-4 border border-gray-200 rounded-lg shadow-sm">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">进行中任务</p>
              <h3 className="text-2xl font-bold text-gray-900 mt-1">2</h3>
            </div>
            <div className="p-3 bg-blue-100 rounded-full">
              <Activity className="h-5 w-5 text-blue-600" />
            </div>
          </div>
          <div className="mt-4 text-xs text-green-600">↑ 较昨日增长12%</div>
        </Card>

        <Card className="p-4 border border-gray-200 rounded-lg shadow-sm">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">已完成项目</p>
              <h3 className="text-2xl font-bold text-gray-900 mt-1">18</h3>
            </div>
            <div className="p-3 bg-green-100 rounded-full">
              <FileText className="h-5 w-5 text-green-600" />
            </div>
          </div>
          <div className="mt-4 text-xs text-green-600">↑ 较上周增长8%</div>
        </Card>

        <Card className="p-4 border border-gray-200 rounded-lg shadow-sm">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">总训练时长</p>
              <h3 className="text-2xl font-bold text-gray-900 mt-1">48.5h</h3>
            </div>
            <div className="p-3 bg-purple-100 rounded-full">
              <Clock className="h-5 w-5 text-purple-600" />
            </div>
          </div>
          <div className="mt-4 text-xs text-red-600">↑ 较上月增长23%</div>
        </Card>
      </div>

      {/* 内容区域 - 表格和图表 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 项目列表 */}
        <div className="lg:col-span-2">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">最近项目</h2>
            <div className="relative">
              <input
                type="text"
                placeholder="搜索项目..."
                className="pl-9 pr-3 py-1 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            </div>
          </div>

          <div className="space-y-3">
            {filteredProjects.length > 0 ? (
              filteredProjects.map((project) => (
                <Card 
                  key={project.id} 
                  className="p-4 border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-all cursor-pointer"
                  onClick={() => handleProjectClick(project.id)}
                >
                  <div className="flex justify-between items-center">
                    <div className="flex items-center space-x-3">
                      <div className={`p-2 rounded-full ${project.type === 'image_classification' ? 'bg-blue-100' : 'bg-green-100'}`}>
                        {project.type === 'image_classification' ? (
                          <Image className="h-5 w-5 text-blue-600" />
                        ) : (
                          <FileText className="h-5 w-5 text-green-600" />
                        )}
                      </div>
                      <div>
                        <h3 className="font-medium text-gray-900">{project.name}</h3>
                        <p className="text-sm text-gray-500">创建于 {project.createdAt}</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <Badge 
                        className={`
                          ${project.status === 'completed' ? 'bg-green-100 text-green-800' : ''}
                          ${project.status === 'running' ? 'bg-blue-100 text-blue-800' : ''}
                          ${project.status === 'pending' ? 'bg-yellow-100 text-yellow-800' : ''}
                        `}
                      >
                        {project.status === 'completed' ? '已完成' : 
                         project.status === 'running' ? '进行中' : '等待中'}
                      </Badge>
                      <ChevronRight className="h-4 w-4 text-gray-400" />
                    </div>
                  </div>
                  {project.progress > 0 && (
                    <div className="mt-3">
                      <div className="flex justify-between text-sm text-gray-500 mb-1">
                        <span>进度</span>
                        <span>{project.progress}%</span>
                      </div>
                      <div className="progress-bar">
                        <div 
                          className={`progress-fill ${project.status === 'completed' ? 'bg-green-500' : 'bg-primary'}`}
                          style={{ width: `${project.progress}%` }}
                        />
                      </div>
                    </div>
                  )}
                </Card>
              ))
            ) : (
              <Card className="p-8 text-center border border-gray-200 rounded-lg">
                <p className="text-gray-500">未找到匹配的项目</p>
              </Card>
            )}
          </div>
        </div>

        {/* 右侧统计图表 */}
        <div className="space-y-6">
          {/* 任务分布 */}
          <Card className="p-4 border border-gray-200 rounded-lg shadow-sm">
            <h3 className="font-semibold text-gray-900 mb-4">任务分布</h3>
            <div className="h-48">
              <PieResponsiveContainer width="100%" height="100%">
                <Pie
                  data={taskDistribution}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  fill="#8884d8"
                  paddingAngle={5}
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                >
                  {taskDistribution.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
              </PieResponsiveContainer>
            </div>
          </Card>

          {/* 训练使用情况 */}
          <Card className="p-4 border border-gray-200 rounded-lg shadow-sm">
            <h3 className="font-semibold text-gray-900 mb-4">本周训练情况</h3>
            <div className="h-56">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={usageStats} margin={{ top: 5, right: 5, bottom: 5, left: 0 }}>
                  <XAxis dataKey="name" fontSize={12} />
                  <YAxis fontSize={12} />
                  <Tooltip />
                  <Bar dataKey="训练时长" fill="#2563eb" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}